import 'package:carousel_slider/carousel_slider.dart';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_van_android/models/news_ugc_data.dart';
import 'package:flutter_van_android/utils/log_util.dart';

import '../models/hot_forum_data.dart';
import '../models/spotLight.dart';
import '../models/ugc_data.dart';
import '../repositories/user_repository.dart';

class DiscoverPage extends StatefulWidget {
  const DiscoverPage({super.key});

  @override
  State<StatefulWidget> createState() {
    return _DiscoverState();
  }
}

class _DiscoverState extends State<DiscoverPage> {
  List<NewsUgcData>? newsUgcList = [];
  List<LightUser>? lightUserList = [];
  List<HotForumItem>? hotForumList = [];
  List<UgcData>? hotArticleList = [];
  int _pageIndex = 1;
  late EasyRefreshController _controller;

  @override
  void initState() {
    super.initState();
    _controller = EasyRefreshController(controlFinishLoad: true);
    _fetchData();
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    SystemChrome.setSystemUIOverlayStyle(const SystemUiOverlayStyle(
      statusBarColor: Colors.transparent, // 透明状态栏
      statusBarIconBrightness: Brightness.dark, // 状态栏图标颜色（黑色）
    ));
    return Scaffold(
        backgroundColor: Colors.white,
        body: SafeArea(
            child: Padding(
                padding: EdgeInsets.only(top: 16),
                child: EasyRefresh(
                  onRefresh: () async {
                    _fetchData();
                  },
                  controller: _controller,
                  onLoad: () async {
                    _pageIndex++;
                    _fetchHotArticleList(_pageIndex);
                  },
                  child: SingleChildScrollView(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        _discoverTitle(),
                        SizedBox(height: 14.h),
                        _newsList(newsUgcList),
                        Container(
                          margin: EdgeInsets.only(top: 17),
                          height: 10.h,
                          color: Color(0xFFF6F6F6),
                        ),
                        SizedBox(height: 16),
                        LightTitle(
                          title: "聚光灯",
                          showBtn: true,
                        ),
                        LightUserCard(lightUserList: lightUserList),
                        LightTitle(
                          title: "论坛",
                          showBtn: true,
                        ),
                        SizedBox(height: 16.h),
                        _hotForumView(),
                        Container(
                          margin: EdgeInsets.only(top: 16.h),
                          height: 10.h,
                          color: Color(0xFFF6F6F6),
                        ),
                        SizedBox(height: 16.h),
                        LightTitle(
                          title: "热帖讨论",
                          showBtn: false,
                        ),
                        // 热门帖子
                        _hotArticleListView()
                      ],
                    ),
                  ),
                ))));
  }

  /// 热门帖子 视图
  ListView _hotArticleListView() {
    return ListView.separated(
        shrinkWrap: true,
        physics: NeverScrollableScrollPhysics(),
        itemBuilder: (context, index) {
          return GestureDetector(
            child: Container(
              margin: EdgeInsets.only(right: 16.w, left: 16.w),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.start,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  SizedBox(height: 16.h),
                  Row(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: [
                      CircleAvatar(
                        radius: 24.r,
                        backgroundImage: NetworkImage(
                            hotArticleList?[index].userDto?.avatar ?? ""),
                      ),
                      SizedBox(width: 12.w),
                      Column(
                        mainAxisAlignment: MainAxisAlignment.start,
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Row(
                            children: [
                              Container(
                                constraints: BoxConstraints(maxWidth: 140.w),
                                child: Text(
                                    hotArticleList?[index].userDto!.nickname ??
                                        "",
                                    maxLines: 1,
                                    overflow: TextOverflow.ellipsis,
                                    style: TextStyle(
                                        color: Color(0xfF333333),
                                        fontSize: 16.sp,
                                        fontWeight: FontWeight.w500)),
                              ),
                              Text("· ${hotArticleList?[index].formattedTime}",
                                  style: TextStyle(
                                    color: Color(0xFF999999),
                                    fontSize: 12.sp,
                                  )),
                            ],
                          ),
                          SizedBox(height: 4.h),
                          Container(
                            constraints: BoxConstraints(maxWidth: 240.w),
                            child: Text(
                              hotArticleList![index].userDto?.introduction ??
                                  "",
                              overflow: TextOverflow.ellipsis,
                              maxLines: 1,
                            ),
                          )
                        ],
                      ),
                      Spacer(flex: 1),
                      Container(
                        width: 48.w,
                        height: 24.h,
                        margin: EdgeInsets.only(top: 10.h),
                        child: TextButton(
                          style: TextButton.styleFrom(
                              padding: EdgeInsets.zero,
                              backgroundColor: Color(0xFF00B68C),
                              shape: RoundedRectangleBorder(
                                  borderRadius: BorderRadius.circular(4.r))),
                          onPressed: () {},
                          child: Text(
                            "关注",
                            style:
                                TextStyle(color: Colors.white, fontSize: 12.sp),
                          ),
                        ),
                      ),
                    ],
                  ),
                  SizedBox(height: 16.h),
                  Row(
                    children: [
                      if (hotArticleList![index].forumDtoList?.isNotEmpty ==
                          true)
                        Container(
                          height: 18.h,
                          decoration: BoxDecoration(
                              color: Color(0xFFF8F8FA),
                              borderRadius: BorderRadius.circular(2.r)),
                          child: Text(
                            hotArticleList![index].forumDtoList![0].forumName ??
                                "",
                            style: TextStyle(
                                fontSize: 10.sp,
                                height: 1.75,
                                color: Color(0xFF00B68C)),
                          ),
                        ),
                    ],
                  ),
                  SizedBox(height: 8.h),
                  Text(
                    hotArticleList![index].content ?? "",
                    maxLines: 5,
                    overflow: TextOverflow.ellipsis,
                    style: TextStyle(
                        fontSize: 14.sp,
                        height: 1.75,
                        color: Color(0xFF333333)),
                  ),
                  if (hotArticleList![index].imageUrlList!.isNotEmpty)
                    SizedBox(
                      height: 188.h,
                      child: ListView.separated(
                          shrinkWrap: true,
                          physics: NeverScrollableScrollPhysics(),
                          itemBuilder: (context, imageIndex) {
                            return GestureDetector(
                              child: Image.network(hotArticleList![index]
                                      .imageUrlList?[imageIndex] ??
                                  ""),
                            );
                          },
                          separatorBuilder: (context, index) =>
                              SizedBox(width: 4.w),
                          itemCount:
                              hotArticleList![index].imageUrlList!.length),
                    ),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.end,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      Container(
                        width: 24.w,
                        height: 24.h,
                        decoration: BoxDecoration(
                            image: DecorationImage(
                                image:
                                    AssetImage('assets/icons/icon_like.png'))),
                      ),
                      Text("认同",
                          style: TextStyle(
                              fontSize: 14.sp, color: Color(0xFF999999)))
                    ],
                  ),
                  SizedBox(height: 16.h)
                ],
              ),
            ),
            onTap: () {},
          );
        },
        separatorBuilder: (context, index) => Container(
              decoration: BoxDecoration(color: Color(0xFFCCCCCC)),
              margin: EdgeInsets.symmetric(horizontal: 16),
              height: 1,
            ),
        itemCount: hotArticleList?.length ?? 0);
  }

  ///热门论坛视图
  SizedBox _hotForumView() {
    return SizedBox(
      height: 315.h,
      child: ListView.separated(
          physics: NeverScrollableScrollPhysics(),
          itemBuilder: (context, index) {
            return GestureDetector(
              child: Container(
                margin: EdgeInsets.only(
                  left: 16.w,
                  right: 16.w,
                ),
                decoration: BoxDecoration(
                    color: Color(0x99F0F4F7),
                    borderRadius: BorderRadius.circular(4.r)),
                padding: EdgeInsets.symmetric(horizontal: 12.w),
                height: 97.h,
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.start,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Flex(
                      direction: Axis.horizontal,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Container(
                            margin: EdgeInsets.only(top: 12.h),
                            child: Text(
                              hotForumList![index].name,
                              maxLines: 1,
                              overflow: TextOverflow.ellipsis,
                              style: TextStyle(color: Color(0xFF00B68C)),
                            )),
                        Container(
                          width: 48.w,
                          height: 24.h,
                          margin: EdgeInsets.only(top: 10.h),
                          child: TextButton(
                            style: TextButton.styleFrom(
                                padding: EdgeInsets.zero,
                                backgroundColor: Color(0xFF00B68C),
                                shape: RoundedRectangleBorder(
                                    borderRadius: BorderRadius.circular(4.r))),
                            onPressed: () {},
                            child: Text(
                              "加入",
                              style: TextStyle(
                                  color: Colors.white, fontSize: 12.sp),
                            ),
                          ),
                        ),
                      ],
                    ),
                    Text(
                      "100位成员·500条讨论",
                      style: TextStyle(
                          color: Color(0xFF999999),
                          height: 1.75,
                          fontSize: 10.sp),
                    ),
                    Container(
                      height: 1.h,
                      decoration: BoxDecoration(color: Color(0xFFF2F2F2)),
                    ),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.start,
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        Container(
                          width: 20.w,
                          height: 20.h,
                          decoration: BoxDecoration(
                              image: DecorationImage(
                                  image: AssetImage(
                                      'assets/icons/icon_red_hot.png'))),
                        ),
                        Expanded(
                          child: Text(
                            maxLines: 1,
                            overflow: TextOverflow.ellipsis,
                            hotForumList![index].introduction,
                            style: TextStyle(
                                fontSize: 14.sp,
                                color: Color(0xFF333333),
                                height: 1.75),
                          ),
                        ),
                      ],
                    )
                  ],
                ),
              ),
            );
          },
          separatorBuilder: (context, index) => SizedBox(
                height: 10.h,
              ),
          itemCount: hotForumList?.length ?? 0),
    );
  }

  Future<void> _fetchData() async {
    try {
      // 并发执行多个请求
      await Future.wait([
        _fetchNews(),
        _fetchLightUserList(),
        _fetchHotForumList(),
        _fetchHotArticleList(1),
      ]);
    } catch (e) {
      LogUtil.e('加载数据发生错误: $e');
    } finally {
      _pageIndex == 1;
      _controller.controlFinishRefresh;
    }
  }

  Future<void> _fetchNews() async {
    var list = await getNewsList();
    var filterList = list
        ?.where((item) => item.title != null && item.title!.isNotEmpty)
        .take(3)
        .toList();
    setState(() {
      newsUgcList = filterList;
    });
  }

  Future<void> _fetchLightUserList() async {
    var list = await getLightUserList();
    setState(() {
      lightUserList = list;
    });
  }

  Future<void> _fetchHotForumList() async {
    var list = await getHotForumList();
    setState(() {
      hotForumList = list;
    });
  }

  Future<void> _fetchHotArticleList(int page) async {
    var list = await getHotPostDiscussion(page: page);
    if (page == 1) {
      setState(() {
        hotArticleList = list;
      });
    } else {
      if (list!.isEmpty) {
        _controller.finishLoad(IndicatorResult.noMore);
      } else {
        setState(() {
          hotArticleList?.addAll(list);
          _controller.finishLoad(IndicatorResult.success);
        });
      }
    }
  }
}

class LightTitle extends StatelessWidget {
  final String title;
  final bool showBtn;

  const LightTitle({super.key, required this.title, required this.showBtn});

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.only(left: 16, right: 16),
      child: Column(
        children: [
          Row(
            children: [
              Text(
                title,
                style: TextStyle(
                    fontSize: 18.sp,
                    color: Color(0xFF333333),
                    fontWeight: FontWeight.bold),
              ),
              Spacer(
                flex: 1,
              ),
              if (showBtn)
                Row(
                  children: [
                    Text(
                      "换一换",
                      style: TextStyle(
                        color: Color(0xff999999),
                        fontSize: 12.sp,
                      ),
                    ),
                    SizedBox(width: 4), // 图标和文字的间距
                    Icon(
                      Icons.refresh,
                      size: 16.sp,
                      color: Color(0xff999999),
                    ),
                  ],
                ),
            ],
          ),
        ],
      ),
    );
  }
}

class LightUserCard extends StatelessWidget {
  const LightUserCard({
    super.key,
    required this.lightUserList,
  });

  final List<LightUser>? lightUserList;

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      height: 240.h,
      child: CarouselSlider(
        items: lightUserList
            ?.map(
              (item) => Container(
                decoration: BoxDecoration(
                    gradient: LinearGradient(
                        begin: Alignment.topCenter,
                        end: Alignment.bottomCenter,
                        colors: [
                          Color(0xe000b68c).withOpacity(0.18),
                          // 使用 ARGB 格式颜色
                          Color(0x80eecf54).withOpacity(0.18),
                          // 使用 ARGB 格式颜色
                        ]),
                    borderRadius: BorderRadius.circular(4.r)),
                child: Stack(
                  alignment: AlignmentDirectional.center,
                  clipBehavior: Clip.none,
                  children: [
                    Positioned(
                        top: -24.h,
                        child: CircleAvatar(
                          radius: 24.r,
                          backgroundImage: NetworkImage(item.userAvatar),
                        )),
                    Positioned.fill(
                        child: Column(
                      mainAxisAlignment: MainAxisAlignment.start,
                      children: [
                        SizedBox(
                          height: 34.h,
                        ),
                        Text(
                          item.userNickname ?? "",
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                          style: TextStyle(
                              fontSize: 16.sp, color: Color(0xFF333333)),
                        ),
                        SizedBox(
                          height: 10.h,
                        ),
                        Expanded(
                          flex: 1,
                          child: Container(
                            padding: EdgeInsets.all(10),
                            width: double.infinity,
                            margin: EdgeInsets.only(
                                left: 10.w, right: 10.w, bottom: 16.h),
                            decoration: BoxDecoration(
                              color: Colors.white,
                              boxShadow: [
                                BoxShadow(
                                  color: Color(0x29000000),
                                  offset: Offset(0, 3.h),
                                  blurRadius: 6.r,
                                )
                              ],
                              borderRadius: BorderRadius.circular(4.r),
                            ),
                            child: Text(
                              item.content ?? "",
                              maxLines: 4,
                              style: TextStyle(
                                fontSize: 12.sp,
                                height: 1.75,
                                overflow: TextOverflow.clip,
                                color: Color(0xFF333333),
                              ),
                            ),
                          ),
                        )
                      ],
                    )),
                    Positioned(
                      width: 48.w,
                      height: 24.h,
                      top: 10.h,
                      // 距顶部的距离
                      right: 10.w,
                      // 距右侧的距离
                      child: TextButton(
                        onPressed: () => {},
                        style: TextButton.styleFrom(
                          padding: EdgeInsets.zero,
                          backgroundColor: Color(0xFF00B68C),
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(4.r),
                          ),
                        ),
                        child: Text(
                          "关注",
                          style:
                              TextStyle(color: Colors.white, fontSize: 12.sp),
                        ),
                      ),
                    )
                  ],
                ),
              ),
            )
            .toList(),
        options: CarouselOptions(
          autoPlay: false,
          aspectRatio: 2.0,
          enlargeCenterPage: true,
          height: 185.h,
        ),
      ),
    );
  }
}

SizedBox _newsList(List<NewsUgcData>? newsUgcList) {
  return SizedBox(
      height: 154.h,
      child: Padding(
        padding: const EdgeInsets.only(left: 16, right: 16),
        child: ListView.separated(
          physics: NeverScrollableScrollPhysics(),
          itemBuilder: (context, index) {
            return GestureDetector(
              child: SizedBox(
                width: double.infinity,
                // 宽度充满父容器
                height: 42.h,
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  // 垂直居中
                  crossAxisAlignment: CrossAxisAlignment.start,
                  // 水平靠左
                  children: [
                    Text(
                      newsUgcList?[index].title ?? '默认值',
                      style: TextStyle(
                        fontSize: 14.sp, // 字体大小
                        fontWeight: FontWeight.bold, // 字体加粗
                        color: Colors.black87, // 字体颜色
                      ),
                      maxLines: 1, // 最大行数
                      overflow: TextOverflow.ellipsis, // 超出部分显示省略号
                    ),
                    SizedBox(height: 4.h), // 间距
                    Row(
                      children: [
                        Text(
                          newsUgcList?[index].userNickname ?? "名字",
                          // 可以替换为实际数据
                          style: TextStyle(
                            fontSize: 12.sp,
                            color: Color(0xff999999),
                          ),
                          maxLines: 1, // 最大行数
                          overflow: TextOverflow.ellipsis, // 超出部分显示省略号
                        ),
                        SizedBox(width: 4.h), // 间距
                        Text(
                          newsUgcList?[index].formattedTime ?? "",
                          style: TextStyle(
                            fontSize: 12.sp,
                            color: Color(0xff999999),
                          ),
                          maxLines: 1, // 最大行数
                          overflow: TextOverflow.ellipsis,
                        )
                      ],
                    ),
                  ],
                ),
              ),
            );
          },
          separatorBuilder: (context, index) => SizedBox(height: 16), // 分隔符高度
          itemCount: newsUgcList?.length ?? 0,
        ),
      ));
}

Row _discoverTitle() {
  return Row(
    mainAxisAlignment: MainAxisAlignment.spaceBetween,
    children: [
      Padding(
        padding: const EdgeInsets.only(left: 16),
        child: Text(
          "资讯",
          style: TextStyle(fontSize: 20.sp, fontWeight: FontWeight.bold),
        ),
      ),
      Padding(
        padding: const EdgeInsets.only(right: 16),
        child: GestureDetector(
          onTap: () {},
          child: Row(
            children: [
              Text("更多",
                  style: TextStyle(
                      color: Color(
                        0xFF999999,
                      ),
                      fontSize: 12.sp)),
              Image.asset(
                "assets/icons/icon_arrow_right.png",
                width: 15.w,
                height: 15.h,
              ),
            ],
          ),
        ),
      )
    ],
  );
}
